//
//  AppDelegate.m
//  laonianbang
//
//  Created by 勇拓 李 on 17/10/9.
//  Copyright © 2017年 zaiyou. All rights reserved.
//

#import "AppDelegate.h"
#import "oldLoginViewController.h"
#import "IQKeyboardManager.h"
#import "OldAccount.h"
#import "oldTabbarViewController.h"
#import <BaiduMapAPI_Base/BMKMapManager.h>
#import "QNuploader.h"
#import <GTSDK/GeTuiSdk.h>
#import "oldMessageSender.h"
#import "WXApi.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApiManager.h"
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
#import <UserNotifications/UserNotifications.h>
#endif

#define BAIDU_MAP_KEY @"rzwLR6t5zhGMS9DlNR6yWWOO0LUH2yGh"

#ifdef DEBUG
#define kGtAppId           @"hwqaYkHYm181G6qs2OelH6"
#define kGtAppKey          @"BfFxLCQzk18RWWdHeYwVt5"
#define kGtAppSecret       @"qnvkFX23FE7aa68ya5DUd2"
#else
#define kGtAppId           @"AReMIYOT4ZAVFWN47JpO43"
#define kGtAppKey          @"CbwB515TOZ6n9LF1EapvF1"
#define kGtAppSecret       @"LxctptdDyb8sNl27ZoSv69"
#endif

#define WXAPPID @"wxb144acf03b132e02"

@implementation MyNavigationController

- ( BOOL ) shouldAutorotate
{
    return NO;
}

- ( UIInterfaceOrientationMask ) supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

- ( UIInterfaceOrientation ) preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    UIGestureRecognizer *gester = self.interactivePopGestureRecognizer;
    gester.delegate = self;
}

#pragma mark - UIGestureRecognizerDelegate

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    
    if ( self.childViewControllers.count == 1 ) {
        return NO;
    }
    
    return YES;
    
}

@end

@interface AppDelegate ()<UIApplicationDelegate, GeTuiSdkDelegate, UNUserNotificationCenterDelegate>
{
    BMKMapManager* _mapManager;
    oldMessageSender *messageSender;
}
@end

@implementation AppDelegate

+ (AppDelegate*)getAppDelegate
{
    return (AppDelegate*)[[UIApplication sharedApplication] delegate];
}
+ (UIWindow*)getMainWindow
{
    AppDelegate* app = [AppDelegate getAppDelegate];
    return app.window;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [self initRootView];
    [self initBaseSettings];
    [self initThirdLab];
    
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

#pragma mark - ourfunc
- (void)initRootView
{
    if(!OLDNetWork.token)
    {
        oldLoginViewController *loginVC= [[oldLoginViewController alloc] initWithNibName:@"oldLoginViewController" bundle:nil];
        MyNavigationController *navi = [[MyNavigationController alloc] initWithRootViewController:loginVC];
        self.window.rootViewController = navi;
        [self.window makeKeyAndVisible];
    }
    else
    {
        
        oldTabbarViewController *tabVC = [oldTabbarViewController new];
        
        self.window.rootViewController = tabVC;
        
        [self.window makeKeyAndVisible];
        
        [ACCOUNT_SINGLETON initAccountInfo:^(BOOL result) {
            if (result) {
                NSLog(@"获取个人信息成功");
            }
            else
            {
                NSLog(@"获取个人信息失败");
            }
        }];
    }
}

- (void)initBaseSettings
{
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = YES;
//    manager.enableAutoToolbar = NO;
    [self setAppColor];
    [self initMessageSender];
}

- (void)initMessageSender
{
    messageSender = [[oldMessageSender alloc] init];
}

- (void)setAppColor
{
    //统一导航条样式
    NSDictionary *dic = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
    [[UINavigationBar appearance] setTitleTextAttributes:dic];
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:OLD_COLOR];
    [[UINavigationBar appearance] setTranslucent:NO];
    
    UIApplication.sharedApplication.statusBarStyle = UIStatusBarStyleLightContent;
}

#pragma mark - 私有方法
+ (void)gotoTab
{
    oldTabbarViewController *tabVC = [oldTabbarViewController new];
    
    [[UIApplication sharedApplication].keyWindow.rootViewController dismissViewControllerAnimated:NO completion:nil];
    UIApplication *app = [UIApplication sharedApplication];
    app.delegate.window.rootViewController = tabVC;
    [app.delegate.window makeKeyAndVisible];
}

#pragma mark - 三方库
- (void)initThirdLab
{
    [self BaiduMap];
    [self initGTSDK];
    [self initWechat];
}

- (void)BaiduMap
{
    _mapManager = [[BMKMapManager alloc]init];
    // 如果要关注网络及授权验证事件，请设定     generalDelegate参数
    BOOL ret = [_mapManager start:BAIDU_MAP_KEY  generalDelegate:nil];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
}

- (void)initGTSDK
{
    [GeTuiSdk startSdkWithAppId:kGtAppId appKey:kGtAppKey appSecret:kGtAppSecret delegate:self];
    // 注册 APNs
    [self registerRemoteNotification];
}

- (void)initWechat
{
    [WXApi registerApp:WXAPPID];
}

/** 注册 APNs */
- (void)registerRemoteNotification {
    /*
     警告：Xcode8 需要手动开启"TARGETS -> Capabilities -> Push Notifications"
     */
    
    /*
     警告：该方法需要开发者自定义，以下代码根据 APP 支持的 iOS 系统不同，代码可以对应修改。
     以下为演示代码，注意根据实际需要修改，注意测试支持的 iOS 系统都能获取到 DeviceToken
     */
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 // Xcode 8编译会调用
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
            if (!error) {
                NSLog(@"request authorization succeeded!");
            }
        }];
        
        [[UIApplication sharedApplication] registerForRemoteNotifications];
#else // Xcode 7编译会调用
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
#endif
    } else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    } else {
        UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert |
                                                                       UIRemoteNotificationTypeSound |
                                                                       UIRemoteNotificationTypeBadge);
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
    }
}

/** SDK启动成功返回cid */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
    //个推SDK已注册，返回clientId
    NSLog(@"\n>>>[GeTuiSdk RegisterClient]:%@\n\n", clientId);
    [[NSUserDefaults standardUserDefaults] setObject:clientId forKey:GT_CID];
}

/** 远程通知注册成功委托 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"\n>>>[DeviceToken Success]:%@\n\n", token);
    
    // 向个推服务器注册deviceToken
    [GeTuiSdk registerDeviceToken:token];
}

/** SDK收到透传消息回调 */
- (void)GeTuiSdkDidReceivePayloadData:(NSData *)payloadData andTaskId:(NSString *)taskId andMsgId:(NSString *)msgId andOffLine:(BOOL)offLine fromGtAppId:(NSString *)appId {
    //收到个推消息
    NSString *payloadMsg = nil;
    if (payloadData) {
        payloadMsg = [[NSString alloc] initWithBytes:payloadData.bytes length:payloadData.length encoding:NSUTF8StringEncoding];
    }
    
    NSString *msg = [NSString stringWithFormat:@"taskId=%@,messageId:%@,payloadMsg:%@%@",taskId,msgId, payloadMsg,offLine ? @"<离线消息1>" : @""];
    NSLog(@"\n>>>[GexinSdk ReceivePayload]:%@\n\n", msg);
    [messageSender receiveMessage:payloadMsg];
}


#pragma mark - Core Data stack

@synthesize persistentContainer = _persistentContainer;

- (NSPersistentContainer *)persistentContainer {
    // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
    @synchronized (self) {
        if (_persistentContainer == nil) {
            _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"laonianbang"];
            [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
                if (error != nil) {
                    // Replace this implementation with code to handle the error appropriately.
                    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                    
                    /*
                     Typical reasons for an error here include:
                     * The parent directory does not exist, cannot be created, or disallows writing.
                     * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                     * The device is out of space.
                     * The store could not be migrated to the current model version.
                     Check the error message to determine what the actual problem was.
                    */
                    NSLog(@"Unresolved error %@, %@", error, error.userInfo);
                    abort();
                }
            }];
        }
    }
    
    return _persistentContainer;
}

#pragma mark - openUrl

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            if(![resultDic[@"result"] isEqualToString: @""] && [resultDic[@"resultStatus"] integerValue] == 9000)
            {
                [messageSender sendMessage:@"支付成功" type:paySuccess];
            }
            else
            {
                [messageSender sendMessage:@"支付失败" type:payFail];
            }
        }];
    }
    else if([url.host isEqualToString:@"pay"])// && [sourceApplication isEqualToString:@"com.tencent.xin"]
    {
        return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
    }
    return YES;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *context = self.persistentContainer.viewContext;
    NSError *error = nil;
    if ([context hasChanges] && ![context save:&error]) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, error.userInfo);
        abort();
    }
}

@end
